/**
 * 一些通用方法
 */
(function (exports) {
  /**
   * 将string字符串转为html对象,默认创一个div填充
   * 因为很常用，所以单独提取出来了
   * @param {String} strHtml 目标字符串
   * @return {HTMLElement} 返回处理好后的html对象,如果字符串非法,返回null
   */
  exports.parseHtml = function (strHtml) {
    if (typeof strHtml !== "string") {
      return strHtml;
    }
    // 创一个灵活的div
    var i,
      a = document.createElement("div");
    var b = document.createDocumentFragment();

    a.innerHTML = strHtml;

    while ((i = a.firstChild)) {
      b.appendChild(i);
    }

    return b;
  };

  /**
   * 将对象渲染到模板
   * @param {String} template 对应的目标
   * @param {Object} obj 目标对象
   * @return {String} 渲染后的模板
   */
  exports.renderTemplate = function (template, obj) {
    return template.replace(/[{]{2}([^}]+)[}]{2}/g, function ($0, $1) {
      return obj[$1] || "";
    });
  };

  /**
   * 添加测试数据
   * @param {String} dom 目标dom
   * @param {Number} dataList 需要添加的数据
   * @param {Boolean} isReset 是否需要重置，下拉刷新的时候需要
   * @param {Number} index 属于哪一个刷新
   */

  // const parser = new DOMParser();
  exports.appendTestData = function (dom, dataList, isReset, index) {
    if (typeof dom === "string") {
      dom = document.querySelector(dom);
    }
    var ids = [];
    if (isReset) {
      dom.innerHTML = "";
    }
    var template = [
      "en-in-feeds.mobicrazy.com",
      "en-in-feeds.obnews.co",
    ].includes(document.domain)
      ? `
    <div class="list-item" index={{index}} id={{d_key}}  exposure_times={{exposure_times}} onclick="handleClick(event,{{d_key}})" >
      <div class='content'>
        <div class="news-title limit-line _{{d_key}}" style="--line-count: 2;">{{title}}</div>
        <div class="news-time" >
          <img class="media-img" src="/flowjs/images/media.svg" alt="" />
          <div class="time-text _{{d_key}} limit-line" style="--line-count: 1;">{{domain}} · {{pubtime}}</div>
        </div>
      </div>
      <div class="news-img"><img class='cover' src="{{image_url}}" alt=""/></div>
    </div>
  `
      : `
    <div class="list-item" index={{index}} id={{d_key}}  exposure_times={{exposure_times}} onclick="handleClick(event,{{d_key}})" >
      <div class="news-img"><img class='cover' src="{{image_url}}" alt=""/></div>
      <div class="news-title limit-line _{{d_key}}" style="--line-count: 3;">{{title}}</div>
      <div class="news-time">
        <img class="media-img" src="/flowjs/images/media.svg" alt="" />
        <div class="time-text _{{d_key}}">{{domain}} · {{pubtime}}</div>
      </div>
    </div>
  `;
    var html = "";
    for (var i = 0; i < dataList.length; i++) {
      const item = dataList[i];
      ids = localStorage.getItem("ids")
        ? JSON.parse(localStorage.getItem("ids"))
        : [];
      if (!ids.includes(item.d_key + "")) {
        html += exports.renderTemplate(template, {
          // iid: item.iid,
          title: item.title,
          image_url: item?.image_list?.[0]?.image_url,
          domain: item.domain,
          pubtime: item.pubtime,
          exposure_times: item.exposure_times,
          index: i + 1 + "",
          d_key: item.d_key,
        });
      }
    }
    var child = exports.parseHtml(html);
    dom.appendChild(child);
    if (
      ["en-in-feeds.mobicrazy.com", "en-in-feeds.obnews.co"].includes(
        document.domain
      )
    ) {
      const covers = document.querySelectorAll(".cover");
      covers.length &&
        covers.forEach((el) => {
          el.onload = function (event) {
            const width = this.naturalWidth;
            const height = this.naturalHeight;
            const ratio = width / height;
            if (ratio > 4 / 3) {
              this.style.setProperty("--cover-width", "auto");
              this.style.setProperty("--cover-height", "100%");
            } else {
              this.style.setProperty("--cover-width", "100%");
              this.style.setProperty("--cover-height", "auto");
            }
          };
        });
    }
    if (!isReset) {
      [].forEach.call(dom.children, (el) => {
        const id = el.getAttribute("id");
        if (!ids.includes(id)) {
          ids.push(id);
        }
      });
      localStorage.setItem("ids", JSON.stringify(ids));
    }

    /*插入广告 bug: 执行55行代码时  广告会发多次请求
    var children = dom.children;
    let count = 0;
    for (let i = 0; i < children.length; i++) {
      count++;
      if (count % 4 === 0 && count !== 0) {
        const adsID =
          window.plainAdsSlotID?.[window.location.hostname]?.[(count / 4 - 1) % 4];
        const defaultID = window.plainAdsSlotID["default"];
        const doc = parser.parseFromString(
          `<div class='plain-ads'>
            <ins class="adsbygoogle"
              style="display:inline-block;width:300px;height:250px"
              data-ad-client="ca-pub-7725717395742252"
              data-ad-slot="${adsID ? adsID : defaultID}">
            </ins>
            <script class='script-copy'>(adsbygoogle = window.adsbygoogle || []).push({});console.log(1111)</script>
          </div>`,
          "text/html"
        );
        const script = doc.querySelector("script");
        const newscript = document.createElement("script");
        newscript.text = script.textContent;
        const plainAds = doc.querySelector(".plain-ads");
        dom.insertBefore(plainAds, dom.children[i]);
        plainAds.appendChild(newscript);
      }
    }
    document.querySelectorAll(".script-copy").forEach((el) => {
      el.remove();
    });*/
  };

  /**
   * 绑定监听事件 暂时先用click
   * @param {String} dom 单个dom,或者selector
   * @param {Function} callback 回调函数
   * @param {String} eventName 事件名
   */
  exports.bindEvent = function (dom, callback, eventName) {
    eventName = eventName || "click";
    if (typeof dom === "string") {
      // 选择
      dom = document.querySelectorAll(dom);
    }
    if (!dom) {
      return;
    }
    if (dom.length > 0) {
      for (var i = 0, len = dom.length; i < len; i++) {
        dom[i].addEventListener(eventName, callback);
      }
    } else {
      dom.addEventListener(eventName, callback);
    }
  };
})((window.CompileTpl = {}));
